package com.helen.ui.bottom;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.helen.adapter.ShoppingCarListAdapter;
import com.helen.db.UserHelper;
import com.helen.entity.CommitProductEntity;
import com.helen.entity.ShoppingCarListEntity;
import com.helen.event.InfoEnent;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseFragment;
import com.helen.ui.order.CommitOrderActivity;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.RecycleViewDivider;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.cache.converter.SerializableDiskConverter;
import com.zhouyou.http.cache.model.CacheMode;
import com.zhouyou.http.cache.model.CacheResult;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2018/4/15.
 * 购物车
 */

public class ShoppingCarFragment extends BaseFragment {
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.cb_check_all)
    CheckBox cbCheckAll;
    @BindView(R.id.tv_goods_price)
    TextView tvGoodsPrice;
    @BindView(R.id.tv_goods_count)
    TextView tvGoodsCount;
    @BindView(R.id.tv_settle_delete)
    TextView tvSettleDelete;
    private List<ShoppingCarListEntity> list = new ArrayList();
    private List<ShoppingCarListEntity> selectList = new ArrayList();
    private View errorView;
    private ShoppingCarListAdapter shoppingCarListAdapter;
    private List<HashMap<String, String>> goodsList = new ArrayList<>();
    private boolean isDeleteCar = false;
    private boolean isSelectGoods = false;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_shopping_car;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.shopping_car);
        getSubTitle().setText(R.string.shopping_car_edit);
        EventBus.getDefault().register(this);
        errorView = getActivity().getLayoutInflater().inflate(R.layout.error_view, (ViewGroup) rvList.getParent(), false);
        shoppingCarListAdapter = new ShoppingCarListAdapter(R.layout.item_shopping_car_list, list, goodsList);
        shoppingCarListAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        swipeRefresh.setRefreshing(true);
        swipeRefresh.setColorSchemeColors(getResources().getColor(R.color.appThemeColor));
        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvList.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_decoration));
        rvList.setAdapter(shoppingCarListAdapter);
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if(UserHelper.getInstance().isLogined()){
                    refresh();
                }
            }
        });

        shoppingCarListAdapter.setRefreshPriceInterface(new ShoppingCarListAdapter.RefreshPriceInterface() {
            @Override
            public void refreshPrice(Map<String, Integer> pitchOnMap) {

                priceControl(pitchOnMap);
            }
        });


        shoppingCarListAdapter.setUpdateCarCountListener(new ShoppingCarListAdapter.OnUpdateCarCountListener() {
            @Override
            public void onCarCountListener(int count, int id) {
                MyLog.e("yang", "count==" + count + ">>>>id==" + id);
                updateCarCountApi(id + "", count + "");
            }
        });

        getSubTitle().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getSubTitle().getText().equals("编辑")) {
                    getSubTitle().setText("完成");
                    tvSettleDelete.setText("删除");
                    isDeleteCar = true;
                } else {
                    getSubTitle().setText("编辑");
                    tvSettleDelete.setText("结算");
                    isDeleteCar = false;
                }

            }
        });

    }

    @Override
    protected void updateViews() {
        MyLog.e("yang","ShoppingCarFragment");
        if(UserHelper.getInstance().isLogined()){
            refresh();
        }

    }


    private void refresh() {
        messageListApi();
    }

    //    获取购物车列表
    private void messageListApi() {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(getActivity()).getId() + "");
        EasyHttp.post(Constants.API_JSONAPI_CARLIST)
                .cacheMode(CacheMode.CACHEANDREMOTEDISTINCT)
                .cacheKey(Constants.API_JSONAPI_CARLIST)
                .cacheDiskConverter(new SerializableDiskConverter())
                .params(params)
                .execute(new SimpleCallBack<CacheResult<String>>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                        swipeRefresh.setRefreshing(false);
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "购物车列表失败==" + e.toString());
                        MToast.makeTextShort(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(CacheResult<String> stringCacheResult) {
                        String data = PhoneUtils.checkResponseFlag2(getActivity(), stringCacheResult.data, TAG);
                        if (data != null && !data.equals("[]")) {
                            list.clear();
                            goodsList.clear();
                            shoppingCarListAdapter.getPitchOnMap().clear();
                            list = new Gson().fromJson(data, new TypeToken<List<ShoppingCarListEntity>>() {
                            }.getType());
                            for (int i = 0; i < list.size(); i++) {
                                HashMap<String, String> map = new HashMap<>();
                                map.put("id", list.get(i).getId() + "");
                                map.put("count", list.get(i).getCount() + "");
                                map.put("price", list.get(i).getPrice() + "");
                                goodsList.add(map);
                            }
                            AllTheSelected();
                            shoppingCarListAdapter.setNewData(list);
                        } else {
                            shoppingCarListAdapter.getData().clear();
                            shoppingCarListAdapter.setEmptyView(errorView);
                            shoppingCarListAdapter.notifyDataSetChanged();
                            cbCheckAll.setChecked(false);

                        }
                    }
                });

    }


    @OnClick({R.id.cb_check_all, R.id.tv_settle_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cb_check_all:
                AllTheSelected();
                break;
            case R.id.tv_settle_delete:
                if (isDeleteCar) {
                    if (isSelectGoods) {
                        MyLog.e("yang", "删除");
                        checkDelete(shoppingCarListAdapter.getPitchOnMap());
                    } else {
                        MToast.makeTextShort(getActivity(), "请选择要删除的商品").show();
                    }
                } else {
                    if (isSelectGoods) {
                        settleGoods(shoppingCarListAdapter.getPitchOnMap());
                        MyLog.e("yang", "结算");
                        if (selectList != null && selectList.size() > 0) {
                            Intent ti = new Intent(getActivity(), CommitOrderActivity.class);
                            ti.putExtra("commitProductEntityList", (Serializable) selectProductList(selectList));
                            ti.putExtra("isShopCar", true);
                            startActivity(ti);
                        }
                    } else {
                        MToast.makeTextShort(getActivity(), "请选择要结算的商品").show();
                    }

                }
                break;
        }

    }


    //     提交订单数据集合
    private List<CommitProductEntity> selectProductList(List<ShoppingCarListEntity> selectList) {
        List<CommitProductEntity> commitProductEntityList = new ArrayList<>();
        for (int i = 0; i < selectList.size(); i++) {
            CommitProductEntity commitProductEntity = new CommitProductEntity();
            commitProductEntity.setProductid(selectList.get(i).getProductid());
            commitProductEntity.setCount(selectList.get(i).getCount());
            commitProductEntity.setExpressprice(selectList.get(i).getExpressPrice());
            commitProductEntity.setDaijin(selectList.get(i).getMaxDaiJin());
            commitProductEntity.setJinbao(selectList.get(i).getMaxJinBao());
            if (selectList.get(i).getIsSpec() == 1) {
                commitProductEntity.setSpecid(selectList.get(i).getSpecid());
            } else {
                commitProductEntity.setSpecid(-1);
            }

            commitProductEntity.setProductImg(selectList.get(i).getProductimg());
            commitProductEntity.setProductName(selectList.get(i).getProductname());
            commitProductEntity.setProductPrice(selectList.get(i).getPrice());
            commitProductEntity.setProductSpec(selectList.get(i).getSpec());
            commitProductEntityList.add(commitProductEntity);
        }
        return commitProductEntityList;
    }


    //全选或反选
    private void AllTheSelected() {
        Map<String, Integer> map = shoppingCarListAdapter.getPitchOnMap();
        boolean isCheck = false;
        boolean isUnCheck = false;
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            if (Integer.valueOf(entry.getValue().toString()) == 1) {
                isCheck = true;
            } else {
                isUnCheck = true;
            }

        }
        if (isCheck == true && isUnCheck == false) {//已经全选,做反选
            for (int i = 0; i < goodsList.size(); i++) {
                map.put(goodsList.get(i).get("id"), 0);
            }
            cbCheckAll.setChecked(false);
        } else if (isCheck == true && isUnCheck == true) {//部分选择,做全选
            for (int i = 0; i < goodsList.size(); i++) {
                map.put(goodsList.get(i).get("id"), 1);
            }
            cbCheckAll.setChecked(true);
        } else if (isCheck == false && isUnCheck == true) {//一个没选,做全选
            for (int i = 0; i < goodsList.size(); i++) {
                map.put(goodsList.get(i).get("id"), 1);
            }
            cbCheckAll.setChecked(true);
        } else if (isCheck == false && isUnCheck == false) {
            for (int i = 0; i < goodsList.size(); i++) {
                map.put(goodsList.get(i).get("id"), 0);
            }
            cbCheckAll.setChecked(false);
        }
        priceControl(map);
        shoppingCarListAdapter.setPitchOnMap(map);
        shoppingCarListAdapter.notifyDataSetChanged();
    }

    //控制价格展示
    private void priceControl(Map<String, Integer> pitchOnMap) {
        int totalCount = 0;
        double totalPrice = 0.00;
        for (int i = 0; i < goodsList.size(); i++) {
            if (pitchOnMap.get(goodsList.get(i).get("id")) == 1) {
                totalCount = totalCount + Integer.valueOf(goodsList.get(i).get("count"));
                double goodsPrice = Integer.valueOf(goodsList.get(i).get("count")) * Double.valueOf(goodsList.get(i).get("price"));
                totalPrice = totalPrice + goodsPrice;
            }
        }
        if (totalCount == 0) {
            isSelectGoods = false;
        } else {
            isSelectGoods = true;
        }
        tvGoodsPrice.setText("￥ " + totalPrice);
        tvGoodsCount.setText("共" + totalCount + "件商品");
    }


    //删除购物车数量
    private void updateCarCountApi(String carid, String count) {
        HttpParams params = new HttpParams();
        params.put("userid", UserHelper.getInstance().getloginEntity(getActivity()).getId() + "");
        params.put("carid", carid);
        params.put("count", count);
        EasyHttp.post(Constants.API_JSONAPI_UPDATECARCOUNT)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "购物车数量修改失败==" + e.toString());
                        MToast.makeTextShort(getActivity(), getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(getActivity(), result, TAG);
                        if (data != null) {
                            MToast.makeTextShort(getActivity(), "修改成功").show();
                        }
                    }
                });
    }


    //    删除购物车
    private void deleteCar(String sid) {
        tvSettleDelete.setEnabled(false);
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(getActivity()).getId() + "");
        params.put("sid", sid);
        EasyHttp.post(Constants.API_JSONAPI_DELETECAR)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.d(TAG, "购物车删除失败==" + e.toString());
                        MToast.makeTextShort(getActivity(), getString(R.string.service_error)).show();
                        tvSettleDelete.setEnabled(true);
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(getActivity(), result, TAG);
                        if (data != null) {
                            MToast.makeTextShort(getActivity(), "删除成功").show();
                            tvSettleDelete.setEnabled(true);
                            messageListApi();

                        }
                    }
                });
    }


    //删除操作
    private void checkDelete(Map<String, Integer> map) {
        List<HashMap<String, String>> waitDeleteList = new ArrayList<>();
        Map<String, Integer> waitDeleteMap = new HashMap<>();
        String sid = "";
        for (int i = 0; i < goodsList.size(); i++) {
            if (map.get(goodsList.get(i).get("id")) == 1) {
                waitDeleteList.add(goodsList.get(i));
                waitDeleteMap.put(goodsList.get(i).get("id"), map.get(goodsList.get(i).get("id")));
                sid += (TextUtils.isEmpty(sid) ? "" : ",") + goodsList.get(i).get("id");
                MyLog.e("yang", "i====" + i);
            }
        }
        goodsList.removeAll(waitDeleteList);
        map.remove(waitDeleteMap);
        priceControl(map);
        MyLog.e("yang", "sid==" + sid);
        deleteCar(sid);
    }


    //    结算
    private void settleGoods(Map<String, Integer> map) {
        selectList.clear();
        for (int i = 0; i < goodsList.size(); i++) {
            if (map.get(goodsList.get(i).get("id")) == 1) {
                selectList.add(list.get(i));
            }
        }
    }

    @Subscribe
    public void onEventMainThread(InfoEnent event) {
        MyLog.e("yang", event.getmMsg());
        String msg = event.getmMsg();
        if(msg.equals(InfoEnent.ADD_CAR_SUCCESS)){
            messageListApi();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
